import React, { Fragment, forwardRef, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Select, Tooltip, Button, Segmented, Modal } from 'antd'
import { SettingOutlined, CloudUploadOutlined, LoadingOutlined, LeftOutlined, ExclamationCircleOutlined, } from '@ant-design/icons';
import './EditorPageNav.scss';
import { deepCloneV2, filterTopicListToNetServe, formatTime, getCurrentDateNs, isEmpty, makeClassNameList, toastShort, useDebounce } from '../../../utils';
import { DocConfig, DocInstance, EditPageNavType, TopicType, UserType } from '../../../utils/types';
import redux from '../../../redux/store';
import comDocContext from '../../../context/DocContext';
import systemApi from '../../../api/system';
import useStateDebounce from '../../../hooks/useStateDebounce';
import BranchSettingPopover from '../../../components/popover/BranchSettingPopover';
import useReSize from "../../../hooks/useResize";
import { DocItem } from '../../slate-editor';
import emitter from '../../../utils/emitter';

interface Props {
    onEditorNavChange?: Function
    onNavigateBack?: Function
}

interface SegmentedOptionType {
    label: string
    value: string
}

const EditorPageNav = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        handleSetDefaultActiveNavType
    }))

    const {
        comDocInstance,
        comDocConfig,
    } = useContext(comDocContext);

    const {
        onEditorNavChange,
        onNavigateBack
    } = props;

    const delayTimer = useRef<any>(null);
    const [navList, setNavList] = useState<SegmentedOptionType[]>([
        {
            label: '规划内容选择',
            value: 'topic'
        },
        {
            label: '投资估算表格',
            value: 'excel'
        },
        {
            label: '规划报告撰写',
            value: 'word'
        }
    ])
    const [activeNavType, setActiveNavType] = useState<EditPageNavType>('topic');
    const [saveLoading, setSaveLoading] = useState(false);
    const [userInfo, setuserInfo] = useState<UserType>(redux.getState().systemConfig.userInfo);
    const debouncedComDocInstance = useStateDebounce(comDocInstance, 1500);
    const lastCachedComDocInstance = useRef<DocInstance>(comDocConfig)
    const debouncedComDocConfig = useStateDebounce(comDocConfig, 2 * 1000);
    const [lastUpdateDate, setLastUpdateDate] = useState(null);
    const delayAllowUpdateDocTimer = useRef(null);

    const handleSetDefaultActiveNavType = (type: EditPageNavType) => {
        setActiveNavType(type);
    }

    const allowUpdateDoc = useRef(false);
    const updateDocTimes = useRef(null);

    useEffect(() => {
        emitter.sub('AutoSwitchNavType', (e: { newNavType: EditPageNavType }) => {
            const { newNavType } = e;
            setActiveNavType(newNavType);
            onEditorNavChange(newNavType);
        })
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current);
            delayAllowUpdateDocTimer.current && clearTimeout(delayAllowUpdateDocTimer.current);
        }
    }, [])

    const formatDateStr = (dateStr: string) => {
        const dateString = '2024-04-21T04:00:33.274Z';
        const date = new Date(dateString);

        const year = date.getFullYear();
        const month = date.getMonth() + 1; // getMonth() 返回的月份是从0开始的，所以加1
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        return formattedDate;
    }

    useEffect(() => {
        console.log("导航栏开始更新---->", comDocInstance)
        if (comDocInstance) {
            lastCachedComDocInstance.current = comDocInstance;
            if (isEmpty(lastUpdateDate)) {
                // console.log("更新时间---->", comDocInstance.updateDate)
                setLastUpdateDate(comDocInstance.updateDate ? formatDateStr(comDocInstance.updateDate) : formatTime(getCurrentDateNs(13)) + '本地存储');
            }
        }
        if (!debouncedComDocInstance) {
            return;
        }
        updateDocTimes.current++;
        console.log("updateDocTimes--->", updateDocTimes.current)
        let tempComDocInstance: DocInstance = deepCloneV2(comDocInstance);
        if (updateDocTimes.current <= 2) {
            return;
        }
        // if (checkTwoDocInstanceEquals(lastCachedComDocInstance.current, comDocInstance)) {
        //     console.log("阻止更新基本信息的网络请求")
        //     return
        // }
        // return toastShort('warning', '即时保存已关闭');
        setSaveLoading(true);
        tempComDocInstance.docId = tempComDocInstance.id;
        if (tempComDocInstance && filterTopicListToNetServe(tempComDocInstance.topicList).length) {
            let tempTopicList = [];
            let { topicList } = tempComDocInstance;
            topicList.forEach(topic => {
                let tempTopic: TopicType = deepCloneV2(topic);
                if (
                    tempTopic.topicSlateDocItemList &&
                    tempTopic.topicSlateDocItemList.length &&
                    tempTopic.topicSlateDocItemList instanceof Array
                ) {
                    //@ts-ignore
                    tempTopic.topicSlateDocItemList = JSON.stringify(tempTopic.topicSlateDocItemList)
                }
                tempTopicList.push(tempTopic);
            })
            tempComDocInstance.topicList = deepCloneV2(tempTopicList);
            // return;
            systemApi.updateProjectTopicList(tempComDocInstance)
                .then(res => {
                    setSaveLoading(false);
                    setLastUpdateDate(getCurrentDateNs());
                })
                .catch(err => {
                    toastShort('error', '数据同步失败，请检查网络连接')
                })
        }
    }, [debouncedComDocInstance])

    useEffect(() => {
        if (!debouncedComDocConfig || !debouncedComDocInstance) {
            return;
        }
        let tempDocConfig: DocConfig = comDocConfig;
        tempDocConfig.id = comDocInstance.id;
        tempDocConfig.docId = comDocInstance.id;
        systemApi.updateDocExtraConfigInfo(tempDocConfig)
            .then(res => {
            })
            .catch(err => {
                console.log("更新失败", err)
            })
    }, [debouncedComDocConfig])


    const [modal, contextHolder] = Modal.useModal();

    const handleCloseEditPage = () => {
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认离开此规划编制页面吗？请确保所有修改已保存',
            okText: '确认',
            cancelText: '取消',
            centered: true,

            onOk: comfrimToCloseEditPage,
        });
    }

    const comfrimToCloseEditPage = () => {
        onNavigateBack && onNavigateBack();
    }

    const handleSwitchEditorNav = (nav: SegmentedOptionType) => {
        //@ts-ignore
        setActiveNavType(nav.value);
        onEditorNavChange && onEditorNavChange(nav.value);
    };

    const containerRef = useRef(null);

    const containerSize = useReSize(containerRef);

    const branchSettingPopoverRef = useRef(null);

    const [branchPopoverPosition, setBranchPopoverPosition] = useState({ clientX: 0, clientY: 0 })

    useEffect(() => {
        // const clientRect = branchBtnRef.current?.getBoundingClientRect();
        // const { top, left } = clientRect;
        // setBranchPopoverPosition({ clientX: left - 220, clientY: top + 28 })
    }, [containerSize])

    const onMouseDown = (e: any) => {
        e.stopPropagation();
    };

    const switchBarTrackLeft = useMemo<number>(() => {
        switch (activeNavType) {
            case 'topic':
                return 3;
                break;
            case 'excel':
                return 121;
                break;
            case 'word':
                return 119 * 2;
                break;
            default:
                break;
        }

    }, [activeNavType])

    return (
        <div
            ref={containerRef}
            className='edit-page-header flex-row'
            onMouseDown={onMouseDown}
            onMouseUp={onMouseDown}
            onClick={onMouseDown}
        >
            <div className='edit-page-header-side edit-page-header-left flex-row'>
                <div
                    className='flex-row header-nav-back-btn'
                    onClick={handleCloseEditPage}
                >
                    <LeftOutlined style={{ fontSize: 16, fontWeight: 900 }} />
                    退出
                </div>
                <div className='project-info flex-col'>
                    <div className='project-name'>{comDocInstance && comDocInstance.name}</div>
                    <div className='project-info-bottom flex-row'>
                        <div style={{ maxWidth: 300 }} className='project-info-text single-line-text'>{userInfo && userInfo.nickName ? userInfo.nickName : userInfo && userInfo.account}</div>
                        <div className='project-info-border-transform'></div>
                        <div className='project-info-text single-line-text'>创建者</div>
                        <div className='project-info-border'></div>
                        <div className='project-info-status flex-row'>
                            {
                                saveLoading ?
                                    <Fragment>
                                        <LoadingOutlined style={{ fontSize: 12, color: '#fff' }} spin />
                                        <div className='project-info-status-text'>保存中</div>
                                    </Fragment>
                                    :
                                    <Fragment>

                                        <CloudUploadOutlined style={{ fontSize: 12, color: '#fff' }} />
                                        <div className='project-info-status-text'> {lastUpdateDate && "保存于：" + formatTime(lastUpdateDate)}</div>
                                    </Fragment>
                            }
                        </div>
                    </div>
                </div>
            </div>
            <div className='flex-row editor-page-nav-switch-bar'>
                {
                    navList.map((item, index) => {
                        return (
                            <div
                                className={makeClassNameList([
                                    'flex-row editor-page-nav-switch-item',
                                ])}
                                key={'nav-item-' + index}
                                onClick={() => handleSwitchEditorNav(item)}
                            >
                                <p style={{ color: activeNavType == item.value ? '#fff' : '#0f6432' }}> {item.label}</p>
                            </div>
                        )
                    })
                }
                <div
                    className='editor-page-nav-switch-bar-track'
                    style={{ left: switchBarTrackLeft }}
                ></div>
            </div>
            <div className='flex-row edit-page-header-side edit-page-header-right flex-row'>
                {/* <div
                    // ref={branchBtnRef}
                >
                    <SettingOutlined
                    //  onClick={handleOpenbranchPopover} 
                    />
                </div> */}
            </div>
            <BranchSettingPopover
                ref={branchSettingPopoverRef}
                clientX={branchPopoverPosition.clientX}
                clientY={branchPopoverPosition.clientY}
            />
            {contextHolder}
        </div>
    )
}

export default forwardRef(EditorPageNav)